import { useStore } from '@tanstack/react-store';
import meStore from '../../store/me';
import { Navigate } from 'react-router-dom';
import Loading from '../ui/Loading';
import { MeRichInfo } from '../../apis/me.types';

type OnlyIfAuthenticatedProps = {
  children: (me: MeRichInfo) => React.ReactNode;
};

// TODO: 高阶化
export default function OnlyIfAuthenticated({ children }: OnlyIfAuthenticatedProps) {
  const meState = useStore(meStore, (state) => state);

  if (meState.state === 'unauthenticated') {
    return <Navigate to="/login" />;
  }

  if (meState.state === 'loading') {
    return <Loading />;
  }

  return <>{children(meState.me)}</>;
}
